$.extend($.fn.datagrid.methods, {  
    addToolbarItem: function(jq, items){  
        return jq.each(function(){  
            var toolbar = $(this).parent().prev("div.datagrid-toolbar");
            for(var i = 0;i<items.length;i++){
                var item = items[i];
                if(item === "-"){
                    toolbar.append('<div class="datagrid-btn-separator"></div>');
                }else{
                    var btn=$("<a href=\"javascript:void(0)\"></a>");
                    btn[0].onclick=eval(item.handler||function(){});
                    btn.css("float","left").appendTo(toolbar).linkbutton($.extend({},item,{plain:true}));
                }
            }
            toolbar = null;
        });  
    },
    removeToolbarItem: function(jq, param){  
        return jq.each(function(){  
            var btns = $(this).parent().prev("div.datagrid-toolbar").children("a");
            var cbtn = null;
            if(typeof param == "number"){
                cbtn = btns.eq(param);
            }else if(typeof param == "string"){
                var text = null;
                btns.each(function(){
                    text = $(this).data().linkbutton.options.text;
                    if(text == param){
                        cbtn = $(this);
                        text = null;
                        return;
                    }
                });
            } 
            if(cbtn){
                var prev = cbtn.prev()[0];
                var next = cbtn.next()[0];
                if(prev && next && prev.nodeName == "DIV" && prev.nodeName == next.nodeName){
                    $(prev).remove();
                }else if(next && next.nodeName == "DIV"){
                    $(next).remove();
                }else if(prev && prev.nodeName == "DIV"){
                    $(prev).remove();
                }
                cbtn.remove();    
                cbtn= null;
            }                        
        });  
    }                 
});



/** 投影项目公共js * */

	function loadComBox(id,url){
		$('#'+id).combobox({   
		    url:url,
		    required:true,
		    valueField:'id',   
		    textField:'bus_name'
		});  
		
	}
	
	/**
	 * 不用校验的comBox
	 * 
	 * @param id
	 * @param url
	 * @return
	 */
	function loadUnCheckComBox(id,url){
		$('#'+id).combobox({   
		    url:url,
		    valueField:'id',   
		    textField:'name'
		});  
		
	}
	
	function ajaxLoad(url,data,callBack){
		$.ajax({
			url:url,
			data:data,
			type:'post',
			error : function(e){
				$.messager.alert('提示','数据load失败！','error')
			},
			success:function(result){
				callBack(result);
			}
		})
		
	}
	
	function  validateChoese(){
		var flag=false;
		if ($('#list_data').datagrid('getSelected')) {
			// 首先如果用户选择了数据，则获取选择的数据集合
			var selectedRow = $('#list_data').datagrid('getSelections');
			flag=true;
		}else{
			$.messager.alert('提示', '请选择一条数据！')
		}
		return flag;
		
	}
	
	
	function addDialogTag(url,title,saveUrl,width,height) {
		if(width==''||width==null){
			width=420;
		}if(height==''||height==null){
			height=300
		}
        $("<div/>").dialog({
            href: url,
            title: "添加"+title,
            height: height,
            width: width,
            modal: true,
            iconCls: "icon-add",
            buttons: [
                         {
                             text: '保存',
                             iconCls: 'icon-add',
                             handler: function () {
                        	 $.messager.progress(); 
                                 var d = $(this).closest('.window-body');
                                 $("#saveForm").form("submit", {
                                     url: saveUrl,
                                     onSubmit: function (param) {
                                         param.action = 'add';
                                         return $(this).form('validate');
                                     },
                                     success: function (result) {
                                         dealAjaxResult(result, function (r) {
                                             d.dialog('destroy');
                                             $.messager.progress('close');
                                            $.messager.alert("提示", "操作成功");
                                            
                                             $("#list_data").datagrid("reload");
                                         })
                                     },error:function (result) {
                                    	 dealAjaxResult(result, function (r) {
                                             d.dialog('destroy');
                                             $.messager.alert("提示", "保存失败");
                                             $("#list_data").datagrid("reload");
                                         })
                                     }
                                 });
                             }
                         },
                         {
                             text: '取消',
                             iconCls: 'icon-cancel',
                             handler: function () { $(this).closest('.window-body').dialog('destroy'); }
                         }
                ],
            onClose: function () {
                $(this).dialog('destroy');
            }
        });
    }
	
	
	function addDialogTree(url,title,saveUrl,width,height) {
		if(width==''||width==null){
			width=420;
		}if(height==''||height==null){
			height=300
		}
        $("<div/>").dialog({
            href: url,
            title: "添加"+title,
            height: height,
            width: width,
            modal: true,
            iconCls: "icon-add",
            buttons: [
                         {
                             text: '保存',
                             iconCls: 'icon-add',
                             handler: function () {
                                 var d = $(this).closest('.window-body');
                                 $("#saveForm").form("submit", {
                                     url: saveUrl,
                                     onSubmit: function (param) {
                                         param.action = 'add';
                                         return $(this).form('validate');
                                     },
                                     success: function (result) {
                                         dealAjaxResult(result, function (r) {
                                             d.dialog('destroy');
                                            $.messager.alert("提示", "操作成功");
                                            
                                            $("#list_data").treegrid("reload").treegrid('clearSelections').treegrid('clearChecked');
                                            $("#treedemo").tree("reload").tree('clearSelections').tree('clearChecked');
                                         })
                                     },error:function (result) {
                                    	 dealAjaxResult(result, function (r) {
                                             d.dialog('destroy');
                                             $.messager.alert("提示", "保存失败");
                                             $("#list_data").treegrid("reload").treegrid('clearSelections').treegrid('clearChecked');
                                             $("#treedemo").tree("reload").tree('clearSelections').tree('clearChecked');
                                         })
                                     }
                                 });
                             }
                         },
                         {
                             text: '取消',
                             iconCls: 'icon-cancel',
                             handler: function () { $(this).closest('.window-body').dialog('destroy'); }
                         }
                ],
            onClose: function () {
                $(this).dialog('destroy');
            }
        });
    }
	
	
	
	/** -- 跳转修改页面前数据验证和数据获取 --* */
	function beforeUpdateDialogTag(url, primKey,title,updateUrl,width,height) {
		if ($('#list_data').datagrid('getSelected')) {
			// 首先如果用户选择了数据，则获取选择的数据集合
			var selectedRow = $('#list_data').datagrid('getSelections');
			if (selectedRow.length > 1) {
				$.messager.alert('提示', '只能选择一条数据！', 'warning');
			} else {
				// url为修改时路径+当前选中的参数
				updateDialogTag(url + selectedRow[0][primKey],title,updateUrl,width,height);
			}
		} else {
			$.messager.alert('提示', '请选择一条数据！')
		}
	}	
	
	/** -- 跳转修改页面前数据验证和数据获取 --* */
	function beforeUpdateDialogTree(url, primKey,title,updateUrl,width,height) {
		if ($('#list_data').treegrid('getSelected')) {
			// 首先如果用户选择了数据，则获取选择的数据集合
			var selectedRow = $('#list_data').treegrid('getSelections');
			if (selectedRow.length > 1) {
				$.messager.alert('提示', '只能选择一条数据！', 'warning');
			} else {
				// url为修改时路径+当前选中的参数
				updateDialogTree(url + selectedRow[0][primKey],title,updateUrl,width,height);
			}
		} else {
			$.messager.alert('提示', '请选择一条数据！')
		}
	}
	
	/** -- 跳转修改页面前数据验证和数据获取 --* */
	function beforeUpdate(url, primKey,title,updateUrl,width,height,id) {
		// alert(id);
		if ($('#list_data').datagrid('getSelected') || id != null) {
			// 首先如果用户选择了数据，则获取选择的数据集合
			var selectedRow = $('#list_data').datagrid('getSelections');
			if (selectedRow.length > 1 && id == null) {
				$.messager.alert('提示', '只能选择一条数据！', 'warning');
			} else {
				// url为修改时路径+当前选中的参数
				if(id == null ){
					id = selectedRow[0][primKey];
				}
				updateDialogTag(url + id,title,updateUrl,width,height);
			}
		} else {
			$.messager.alert('提示', '请选择一条数据！')
		}
	}
	
  function updateDialogTag(url,title,updateUrl,width,height) {
		if(width==''||width==null){
			width=420;
		}if(height==''||height==null){
			height=300
		}
	  $("<div/>").dialog({
          href: url,
          title: "修改"+title,
          height: height,
          width: width,
          modal: true,
          iconCls: "icon-edit",
          buttons: [
                       {
                           text: '保存',
                           iconCls: 'icon-edit',
                           handler: function () {
                               var d = $(this).closest('.window-body');
                               $("#saveForm").form("submit", {
                                   url: updateUrl,
                                   onSubmit: function (param) {
                                       param.action = 'edit';
                                       return $(this).form('validate');
                                   },
                                   success: function (result) {
                                       dealAjaxResult(result, function (r) {
                                           d.dialog('destroy');
                                           $.messager.alert("提示", "操作成功");
                                           $("#list_data").datagrid("reload").datagrid('clearSelections').datagrid('clearChecked');
                                       })
                                   }
                               });
                           }
                       },
                       {
                           text: '取消',
                           iconCls: 'icon-cancel',
                           handler: function () { $(this).closest('.window-body').dialog('destroy'); }
                       }
              ],
          onClose: function () {
		  $('#list_data').datagrid('clearSelections');
              $(this).dialog('destroy');
          }
      });

  }
  
  //弹出生成二维码
  function QRCodeDialogTag(url,title,updateUrl,width,height) {
		if(width==''||width==null){
			width=260;
		}if(height==''||height==null){
			height=260;
		}
	  $("<div/>").dialog({
        href: url,
        title: "比赛"+title,
        height: height,
        width: width,
        modal: true,
        iconCls: "icon-edit",
        buttons: [
                     {
                         text: '关闭',
                         iconCls: 'icon-cancel',
                         align:'center',
                         handler: function () { $(this).closest('.window-body').dialog('destroy'); }
                     }
            ],
        onClose: function () {
		  $('#list_data').datagrid('clearSelections');
            $(this).dialog('destroy');
        }
    });

}
	  
  
  
  function updateDialogTree(url,title,updateUrl,width,height) {
		if(width==''||width==null){
			width=420;
		}if(height==''||height==null){
			height=300
		}
	  $("<div/>").dialog({
        href: url,
        title: "修改"+title,
        height: height,
        width: width,
        modal: true,
        iconCls: "icon-edit",
        buttons: [
                     {
                         text: '保存',
                         iconCls: 'icon-edit',
                         handler: function () {
                             var d = $(this).closest('.window-body');
                             $("#saveForm").form("submit", {
                                 url: updateUrl,
                                 onSubmit: function (param) {
                                     param.action = 'edit';
                                     return $(this).form('validate');
                                 },
                                 success: function (result) {
                                     dealAjaxResult(result, function (r) {
                                         d.dialog('destroy');
                                         $.messager.alert("提示", "操作成功");
                                         $("#list_data").treegrid("reload").treegrid('clearSelections').treegrid('clearChecked');
                                         $("#treedemo").tree("reload").tree('clearSelections').tree('clearChecked');
                                     })
                                 }
                             });
                         }
                     },
                     {
                         text: '取消',
                         iconCls: 'icon-cancel',
                         handler: function () { $(this).closest('.window-body').dialog('destroy'); }
                     }
            ],
        onClose: function () {
            $(this).dialog('destroy');
        }
    });

}
  
	// 带重置密码的 修改
	
	function beforeUpdateDialogRest(url, primKey,title,updateUrl,width,height,id) {
		// alert(id);
		if ($('#list_data').datagrid('getSelected') || id != null) {
			// 首先如果用户选择了数据，则获取选择的数据集合
			var selectedRow = $('#list_data').datagrid('getSelections');
			if (selectedRow.length > 1) {
				$.messager.alert('提示', '只能选择一条数据！', 'warning');
			} else {
				// url为修改时路径+当前选中的参数
				// alert(selectedRow[0][primKey]);
				if(id == null ){
					id = selectedRow[0][primKey];
				}
				updateDialogRest(url + id,title,updateUrl,width,height , id);
			}
		} else {
			$.messager.alert('提示', '请选择一条数据！')
		}
	}
	// 重置密码
	function updateDialogRest(url,title,updateUrl,width,height,id) {
		var  urlRest = '/MSInfoPlat/tuser/restpass.do?id='+id
		if(width==''||width==null){
			width=420;
		}if(height==''||height==null){
			height=300
		}
	  $("<div/>").dialog({
          href: url,
          title: "修改"+title,
          height: height,
          width: width,
          modal: true,
          iconCls: "icon-edit",
          buttons: [
                       {
                           text: '保存',
                           iconCls: 'icon-edit',
                           handler: function () {
                               var d = $(this).closest('.window-body');
                               $("#saveForm").form("submit", {
                                   url: updateUrl,
                                   onSubmit: function (param) {
                                       param.action = 'edit';
                                       return $(this).form('validate');
                                   },
                                   success: function (result) {
                                       dealAjaxResult(result, function (r) {
                                           d.dialog('destroy');
                                           $.messager.alert("提示", "操作成功");
                                           $("#list_data").datagrid("reload").datagrid('clearSelections').datagrid('clearChecked');
                                       })
                                   }
                               });
                           }
                       },
                       {
                           text: '重置密码',
                           iconCls: 'icon-cancel',
                           handler: function () { 
                    	   $.ajax( {
                    			cache : false,
                    			type : "POST",
                    			url : urlRest,
                    			async : false,
                    			error : function(request) {
                    		   			$.messager.alert('提示','重置失败！','error');
                    			},
                    			success : function(data) {
                    				    $.messager.alert("提示", "操作成功");
                    			}
                    		});
                       }
                       },
                       {
                           text: '取消',
                           iconCls: 'icon-cancel',
                           handler: function () { $(this).closest('.window-body').dialog('destroy'); }
                       }
              ],
          onClose: function () {
		  $('#list_data').datagrid('clearSelections');
              $(this).dialog('destroy');
          }
      });

  }
	

	// 日期转换成 'yyyy-mmm-dd'
	function ChangeDateToString(DateIn)

	{

		var Year = 0;

		var Month = 0;

		var Day = 0;

		var CurrentDate = "";

		// 初始化时间

		Year = DateIn.getFullYear();

		Month = DateIn.getMonth() + 1;

		Day = DateIn.getDate();

		CurrentDate = Year + "-";

		if (Month >= 10)

		{

			CurrentDate = CurrentDate + Month + "-";

		}

		else

		{

			CurrentDate = CurrentDate + "0" + Month + "-";

		}

		if (Day >= 10)

		{

			CurrentDate = CurrentDate + Day;

		}

		else

		{

			CurrentDate = CurrentDate + "0" + Day;

		}

		return CurrentDate;

	}



	// 日期转换成 'yyyy-mmm-dd'
	function getCurrMonth()

	{

		var Year = 0;

		var Month = 0;

		var Day = 0;

		var CurrentDate = "";

		// 初始化时间
		var DateIn=new Date();
		
		Year = DateIn.getFullYear();

		Month = DateIn.getMonth() + 1;

		Day = DateIn.getDate();

		CurrentDate = Year + "-";

		if (Month >= 10)

		{

			CurrentDate = CurrentDate + Month + "-";

		}

		else

		{

			CurrentDate = CurrentDate + "0" + Month ;

		}


		return CurrentDate;

	}



	/*
	 * zf 处理ajax返回值通用处理方法
	 * 
	 */
	function dealAjaxResult(result, okFun) {
	    if (result == "nosession") {
	        $.relogin();
	    }
	    else if (result == "ok") {
	        okFun(result);
	    }
	    else {
	    	 $.messager.alert("错误", result);
	    }
	}


	/**
	 * @author 陈磊
	 * 
	 * @requires jQuery
	 * 
	 * 改变jQuery的AJAX默认属性和方法
	 */
	$.ajaxSetup({
	    // type: 'POST',
	    error: function (XMLHttpRequest, textStatus, errorThrown) {
	        $.messager.progress('close');
	        $.messager.alert('错误', XMLHttpRequest.responseText);
	    }
	});


	
	// 人民币金额转大写程序 JavaScript版
	// @autor cl
	
	function numToCny(n)   
	{  
	    var fraction = ['角', '分'];  
	    var digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];  
	    var unit = [ ['元', '万', '亿'], ['', '拾', '佰', '仟']  ];  
	    var head = n < 0? '负': '';  
	    n = Math.abs(n);  

	    var s = '';  

	    for (var i = 0; i < fraction.length; i++)   
	    {  
	        s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');  
	    }  
	    s = s || '整';  
	    n = Math.floor(n);  

	    for (var i = 0; i < unit[0].length && n > 0; i++)   
	    {  
	        var p = '';  
	        for (var j = 0; j < unit[1].length && n > 0; j++)   
	        {  
	            p = digit[n % 10] + unit[1][j] + p;  
	            n = Math.floor(n / 10);  
	        }  
	        s = p.replace(/(零.)*零$/, '').replace(/^$/, '零')  + unit[0][i] + s;  
	    }  
	    return head + s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整');  
	}
	
	function addOtherPos(url,title,saveUrl,width,height) {
		if(width==''||width==null){
			width=420;
		}if(height==''||height==null){
			height=300
		}
        $("<div/>").dialog({
            href: url,
            title: title,
            height: height,
            width: width,
            modal: true,
            iconCls: "icon-add",
            buttons: [
                         {
                             text: '保存',
                             iconCls: 'icon-add',
                             handler: function () {
                        	 	$.messager.progress(); 
                                 var d = $(this).closest('.window-body');
                                 $("#saveForm").form("submit", {
                                     url: saveUrl,
                                     onSubmit: function (param) {
                                         param.action = 'add';
                                         return $(this).form('validate');
                                     },
                                     success: function (result) {
                                         dealAjaxResult(result, function (r) {
                                             d.dialog('destroy');
                                             $.messager.progress('close');
                                            $.messager.alert("提示", "操作成功");
                                            
                                             $("#list_dataPos").datagrid("reload");
                                         })
                                     },error:function (result) {
                                    	 dealAjaxResult(result, function (r) {
                                             d.dialog('destroy');
                                             $.messager.alert("提示", "保存失败");
                                             $("#list_dataPos").datagrid("reload");
                                         })
                                     }
                                 });
                             }
                         },
                         {
                             text: '取消',
                             iconCls: 'icon-cancel',
                             handler: function () { $(this).closest('.window-body').dialog('destroy'); }
                         }
                ],
            onClose: function () {
                $(this).dialog('destroy');
            }
        });
    }

	function updateDialogTag(url,title,updateUrl,width,height) {
		if(width==''||width==null){
			width=420;
		}if(height==''||height==null){
			height=300
		}
	  $("<div/>").dialog({
          href: url,
          title: title,
          height: height,
          width: width,
          modal: true,
          iconCls: "icon-edit",
          buttons: [
                       {
                           text: '保存',
                           iconCls: 'icon-edit',
                           handler: function () {
                    		$.messager.progress(); 
                               var d = $(this).closest('.window-body');
                               $("#saveForm").form("submit", {
                                   url: updateUrl,
                                   onSubmit: function (param) {
                                       param.action = 'edit';
                                       return $(this).form('validate');
                                   },
                                   success: function (result) {
                                       dealAjaxResult(result, function (r) {
                                           d.dialog('destroy');
                                           $.messager.progress('close');
                                           $.messager.alert("提示", "操作成功");
                                           $("#list_data").datagrid("reload").datagrid('clearSelections').datagrid('clearChecked');
                                       })
                                   }
                               });
                           }
                       },
                       {
                           text: '取消',
                           iconCls: 'icon-cancel',
                           handler: function () { $(this).closest('.window-body').dialog('destroy'); }
                       }
              ],
          onClose: function () {
		  $('#list_data').datagrid('clearSelections');
              $(this).dialog('destroy');
          }
      });

  }
	
	function getPath(){
  		var curWwwPath = window.document.location.href;
  		var pathName =  window.document.location.pathname;
  		var pos = curWwwPath.indexOf(pathName);
  		var localhostPaht = curWwwPath.substring(0,pos);
  		var projectName = pathName.substring(0,pathName.substr(1).indexOf('/')+1);
  		return (localhostPaht + projectName);
  		}	
	
	function resetSearch(){
　		
		var queryParams = $('#list_data').datagrid('options').queryParams;
		$.each($("form[name=queryForm]").serializeArray(), function(idx, item) {
			if (item.name) {
				document.getElementById(item.name).value = "";
				queryParams[item.name] = "";
			}
		});
		
		$("#basname").combo("setValue",null).combo("setText",null);
		$("#smname").combo("setValue",null).combo("setText",null);
		$("#deptname").combo("setValue",null).combo("setText",null);
		
		// 重置查询页数为1
		var curr_time = new Date();
　		$("#begin").val(begdin(curr_time));
　		$("#end").val(end(curr_time));
　		
　		$.each($("form[name=queryForm]").serializeArray(), function(idx, item) {
			if (item.name) {
				// alert( item.value);
				queryParams[item.name] = item.value;
			}
		});
		$('#list_data').datagrid('options').pageNumber = 1;
		var p = $('#list_data').datagrid('getPager');
		if (p) {
			$(p).pagination( {
				pageNumber : 1
			});
		}
		// 刷新列表数据
		$('#list_data').datagrid('reload');
		
	}
	
	function end(date){
        var y = date.getFullYear();
        var m = date.getMonth()+1;
        var d = date.getDate();
        
         if(m == 2){
			        d= d % 4 == 0 ? 29 : 28;
			    }
			    else if(m == 1 || m == 3 || m == 5 || m == 7 || m == 8 || m == 10 || m == 12){
			        // 月份为：1,3,5,7,8,10,12 时，为大月.则天数为31；
			        d= 31;
			    }
			    else{
			        // 其他月份，天数为：30.
			        d= 30;
			    }
         var d = date.getDate();
         // 当月份为二月时，根据闰年还是非闰年判断天数
        return y+'-'+(m<10?('0'+m):m)+'-'+(d<10?('0'+d):d);
    }
    function begdin(date){
     	var y = date.getFullYear();
        var m = date.getMonth()+1;
        var getd = date.getDate();
        var d = 1;
        if(getd<2){
        m = parseInt(m) -1; 
        };
        if(m ==0 ){
         y = y-1;
         m = 12;
         };
        return y+'-'+(m<10?('0'+m):m)+'-'+(d<10?('0'+d):d);
    }
	
